'use strict';

app.controller('group_detail_Ctrl', ['$scope','$http','loginService','$routeParams', function($scope,$http,loginService,$routeParams,uiGmapGoogleMapApi, uiGmapIsReady){
	
 //=====================paging groups of user======================
    $scope.nbr_rows_groups=0;
    $scope.entryLimit_group = 5
    $scope.offset_group = 0;
    $scope.disablePrev_group = true;
    $scope.disableNext_group = false;
    $scope.page_now_group = 1;
    //================================================================
	
	 //=====================paging events of group ======================
	$scope.nbr_rows_eg=0;
    $scope.entryLimit_eg = 5
    $scope.offset_eg = 0;
    $scope.disablePrev_eg = true;
    $scope.disableNext_eg = false;
    $scope.page_now_eg = 1;
    //================================================================
	
	 $scope.init = function() {
		     loginService.islogged(); 
			 $scope.link = loginService.getLink();
	    	 $scope.getGroupByGroupId($routeParams.id);
	    };
	 
	 
	 
	 $scope.getGroupByGroupId = function(id){ 
	        $http.get($scope.link+'group/'+id).success(function(data){
	        	var loc = data.data.location;
	        	var loc_Str = loc.toString();
	        	var arr  = loc_Str.split(",") ; 
	        	$scope.longtitude = arr[1];
	        	$scope.latitude = arr[0];
				
				$scope.name_group= data.data.name;
	        	console.log('a group is loaded');
	        	$scope.group = data;
	        	$scope.getUserById_group(data.data.owner_id,1);
	        	
	        	$scope.getUsersByGroupId(id);
				$scope.getEventsByGroupId(id);
				$scope.cities = [];
			    $scope.cities.push({ 
						"name" : data.data.name,
						"interest"  : data.data.interest,
						"lat" : arr[0],
						"long" : arr[1],
						"icon":"http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
					});
				$scope.getGroupNearBy($scope.longtitude,$scope.latitude,10,0,100);
	        }).error(function(data, status, config) {
	        	console.log('can not load group with group id : ' + id);
	 });
	 }
	
	$scope.getGroupNearBy = function(lon, lat,rad,start,count){ 
				
				//http://52.28.65.15:8182/v1/admin/nearbygroup/105.778097/21.019087/1000/0/100
			        $http.get($scope.link+'nearbygroup/'+lon+'/'+lat+'/'+rad+'/'+start+'/'+count+'/').success(function(data){
			        	console.log('all group nearby is loaded');
			    
					  var i = 0;
					  var red_dot = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
					  var blue_dot = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
					
					  angular.forEach(data.data,function(){
						var loc = data.data[i].location;
						var loc_Str = loc.toString();
						var arr  = loc_Str.split(",");
						
						var dot=red_dot;
						
						if($scope.name_group==data.data[i].name){
							dot=blue_dot;
						}
					    $scope.cities.push({ 
								"name" : data.data[i].name,
								"interest"  : data.data[i].interest,
								"lat" : arr[0],
								"long" : arr[1],
								"icon":dot
							});

					  i++;
					  })
					
					 
					  $scope.getNearByMap();
			        }).error(function(data, status, config) {
		        	console.log('can not load group nearby');
		           });
			    
			 }
	
	
	     $scope.getNearByMap = function(){
				 var mapOptions = {
				zoom: 12,
				center: new google.maps.LatLng($scope.latitude, $scope.longtitude),
				mapTypeId: google.maps.MapTypeId.TERRAIN
			   }

			$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
				google.maps.event.addListener($scope.map, 'click', function(e) {
				//alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
				$scope.latitude = e.latLng.lat();
				$scope.longtitude = e.latLng.lng();
				$scope.getGroupNearBy(e.latLng.lng(),e.latLng.lat(),10,0,100);
				
			  });
			
			$scope.markers = [];
			
			 var infoWindow = new google.maps.InfoWindow();
			 
			  var createMarker = function (info){
				
				var marker = new google.maps.Marker({
					map: $scope.map,
					position: new google.maps.LatLng(info.lat, info.long),
					title: info.name,
					icon:info.icon
				});
				marker.content = '<div class="infoWindowContent">' + info.interest + '</div>';
				
				google.maps.event.addListener(marker, 'click', function(){
					infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
					infoWindow.open($scope.map, marker);
				});
				
				$scope.markers.push(marker);
				
			}
			
			
			
				 var i = 0;
				 angular.forEach($scope.cities, function(value, key) {
				   createMarker($scope.cities[i]);
				   i++;
				})
					  
			  $scope.openInfoWindow = function(e, selectedMarker){
				e.preventDefault();
				google.maps.event.trigger(selectedMarker, 'click');
			}
		 
	 };
	
	$scope.getUsersByGroupId = function(id){
		        $http.get($scope.link+'user_group/'+id).success(function(data){
		        	console.log('list users by group is loaded');
		        	$scope.lst_user = data;
		        	$scope.nb_users = data.data.members_list.length;
		        	$scope.jsonToArray_members(data);
		        	pageResult_group($scope);
		        }).error(function(data, status, config) {
		        	console.log('can not load list of users by group Id : ' + id);
		 });
		 }
	
		 $scope.jsonToArray_members = function (data) {
				$scope.b = new Array();
				var i = 0;
				angular.forEach(data.data.members_list,function(){
					$scope.b[i]=new Array(2);
		    		$scope.b[i][0] =  data.data.members_list[i].name;
					$scope.b[i][1] =  data.data.members_list[i].id;
		            i++;
		        })
		        $scope.nbr_rows_groups = i ;
				
				$scope.b_ini= angular.copy($scope.b);
			}
	
	
	 $scope.getUserById_group = function(id, type){
				var name = 'not_name';
			        $http.get($scope.link+'users/'+id).success(function(data){
			        	console.log('owner is loaded');
			            if(type==1){
			        	  $scope.owner = data;
			            }
			        	
			         
			        	// $scope.getGroupsByUserId(data.data.id);
			        }).success(function(data, status, config) {
			        	 $scope.name = data.data.first_name + ' ' + data.data.last_name;
			        });
			    
			    
			 }
	 

	$scope.getEventsByGroupId = function(id){
		        $http.get($scope.link+'group_event/'+id).success(function(data){
		        	console.log('list events by group is loaded');
		        	$scope.lst_events = data;
		        	$scope.nb_events = data.data.eventsList.length;
		        	$scope.jsonToArray_events(data);
		        	pageResult_group_event($scope);
		        }).error(function(data, status, config) {
		        	console.log('can not load list of events by group Id : ' + id);
		           });
	}
	
	
       $scope.jsonToArray_events = function (data) { //alert(JSON.stringify(data));
					$scope.d = new Array();
					var i = 0;
					angular.forEach(data.data.eventsList,function(){
						$scope.d[i]=new Array(2);
			    		
						$scope.d[i][1] =  data.data.eventsList[i].id;
						$scope.d[i][0] =  data.data.eventsList[i].name;
						
			            i++;
			        })
			        $scope.nbr_rows_eg = i ;
					$scope.d_ini= angular.copy($scope.d);
	 }	
	
	
     $scope.$watch('d', function() {   
			if( ($scope.page_now_eg==1)  &&  ($scope.nbr_rows_eg <= $scope.entryLimit_eg) )
			 {
			 $scope.disableNext_eg = true;
			 }
			
		}); 	
	
	 $scope.$watch('b', function() {   
			if( ($scope.page_now_group==1)  &&  ($scope.nbr_rows_groups <= $scope.entryLimit_group) )
			 {
			 $scope.disableNext_group = true;
			 }
			
		}); 
	 
		// switch to next page
		$scope.nextPage_group = function() { 
	       nextPage_common_group($scope);
		}

		// switch to previous page
		$scope.previousPage_group = function() {
	      previousPage_common_group($scope);
		}
	
	   // switch to next page
		$scope.nextPage_eg = function() { 
	       nextPage_evg($scope);
		}

		// switch to previous page
		$scope.previousPage_eg = function() {
	      previousPage_evg($scope);
		}
	
		
	
}])